package cn.com.dhc.danlu.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.provider.Settings.Secure;

import com.danlu.lib.net.update.DownloadTaskDelegate;
import com.danlu.lib.net.update.UpgradeProxy;
import com.tbruyelle.rxpermissions.RxPermissions;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.global.DanluApplication;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.PreferenceUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.request.mydl.version.AppVersionCompareRequest;
import cn.com.hd.mall.web.webservices.entity.response.mydl.version.AppVersionCompareResponse;
import cn.com.hd.mall.web.webservices.entity.utils.DanluConstants;
import rx.Subscriber;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

public class CheckVersionDelegate {
    /**
     * 是否更新
     */
    private static final String CLIENT_OBSOLETED = "1";
    /**
     * 是否强制更新
     */
    private static final String FORCE_UP_GRADE = "1";
    /**
     * 普通更新
     */
    private static final String NORMAL_UPDATE = "0";
    /**
     * apk更新地址
     */
    private static String URL = "";
    private static boolean isLoginShowUpdateDialog = false;
    /**
     * 调用方上下文
     */
    private Context fromActivity;
    /**
     * 存储用共同类
     */
    private PreferenceUtils preferenceUtils;

    private String latestVersion;
    /**
     * 版本检查监听器
     */
    private CheckVersionListener checkVersionListener = null;
    private OnWhenActiveListener mCallback;

    private RxPermissions rxPermissions;

    public CheckVersionDelegate (Activity fromActivity, CheckVersionListener listener) {
        //        this.danluTaskProxy = danluTaskProxy;
        this.fromActivity = fromActivity;
        this.checkVersionListener = listener;
        @SuppressLint("HardwareIds")
        String devId = Secure.getString (fromActivity.getContentResolver (), Secure.ANDROID_ID);
        preferenceUtils = new PreferenceUtils (fromActivity, devId);
        rxPermissions = new RxPermissions (fromActivity);
    }

    /**
     * 请求版本号
     */
    public void getVersion () {
        // 设置初始化版本号
        preferenceUtils.setVersion (CommonUtils.getAppVersioName (DanluApplication.get ()));
        // 请求版本信息
        AppVersionCompareRequest request = new AppVersionCompareRequest ();
        request.setToken (agent.getToken ());
        request.setClientVersion (preferenceUtils.getVersion ());
        request.setOsCode (DanluConstants.Constants.OS_CODE);
        request.setEquipmentCode (DanluConstants.Constants.EQUIPMENT_CODE);
        request.setAppType (DanluConstants.Constants.APP_TYPE_0);
        agent.getApi ().getVersion (request)
                .compose (OperatorUtils.<AppVersionCompareResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<AppVersionCompareResponse> () {
                    @Override
                    protected void onSuccess (AppVersionCompareResponse model) {
                        latestVersion = model.getLatestVersion ();
                        URL = model.getDownloadUrl ();// 获取apk下载url
                        // 是否有更新
                        if (CLIENT_OBSOLETED.equals (model.getClientObsoleted ())) {
                            // 强制更新
                            if (FORCE_UP_GRADE.equals (model.getForceUpgrade ())) {
                                createFUGUpdateDialog ();
                            } else if (NORMAL_UPDATE.equals (model// 普通更新
                                    .getForceUpgrade ())) {
                                isLoginOrisPop ();// 是否弹出更新对画框
                            }
                        } else {
                            //当前无更新 也需要检查下当前用户手机号是否激活
                            if (null != mCallback) {
                                mCallback.checkActive ();
                            }
                        }
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        if (null != mCallback) {
                            mCallback.checkActive ();
                        }
                    }
                });
    }

    /**
     * 判断用户是否登录及是否弹出过对话框
     */

    private void isLoginOrisPop () {
        if (!isLoginShowUpdateDialog) {
            createIsUpdateDialog ();
            isLoginShowUpdateDialog = true;
        }
    }

    /**
     * 创建是否更新对话框
     */
    private void createIsUpdateDialog () {
        ViewDialog.Builder builder = new ViewDialog.Builder (fromActivity);
        // 设置标题
        // builder.setTitle(R.string.is_update);
        // 设置信息
        builder.setMessage (R.string.normal_update);
        // 设置Positive按钮点击监听
        builder.setPositiveButton (R.string.background_download, new DialogInterface.OnClickListener () {

            @Override
            public void onClick (DialogInterface dialog, int which) {
                //                Download.DLoadBindService (fromActivity, URL);
                checkPermission (false);
                // 对话框关闭
                dialog.dismiss ();
            }
        });
        // 设置Negative按钮点击监听
        builder.setNegativeButton (R.string.go_use, new DialogInterface.OnClickListener () {

            @Override
            public void onClick (DialogInterface dialog, int which) {
                // 对话框关闭
                dialog.dismiss ();
                if (null != mCallback) {
                    mCallback.checkActive ();
                }
            }
        });
        // 创建对话框并显示
        if (null != fromActivity && !((Activity) fromActivity).isFinishing ()) {
            builder.create ().show ();
            isLoginShowUpdateDialog = true;
        }
    }

    public void checkPermission (final boolean isForceUpdate) {
        if (DownloadTaskDelegate.newInstance ().isDownloading ()) {
            ToastUtil.getInstance ().show (R.string.apk_downloading);
            return;
        }
        rxPermissions.request (Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe (new Subscriber<Boolean> () {
                    @Override
                    public void onCompleted () {

                    }

                    @Override
                    public void onError (Throwable e) {

                    }

                    @Override
                    public void onNext (Boolean granted) {
                        if (granted) {
                            download (isForceUpdate);
                        } else {
                            ToastUtil.getInstance ().show ("下载写入文件权限被拒绝");
                        }
                    }
                });
    }

    private void download (boolean isForceUpdate) {
        String baseUrl = URL.substring (0, URL.lastIndexOf ("/") + 1);
        String downloadUrl = URL.substring (URL.lastIndexOf ("/") + 1, URL.length ());
        UpgradeProxy.Builder builder = new UpgradeProxy.Builder ()
                .baseUrl (baseUrl)
                .downloadUrl (downloadUrl)
                .apkVersion (latestVersion)
                .apkMD5 (null)
                .contentTitle (fromActivity.getString (R.string.app_name))
                .context (fromActivity)
                .notificationSmallIcon (R.mipmap.ic_launcher)
                .isForceUpdate (isForceUpdate)
                .interactionType (isForceUpdate ? UpgradeProxy.InteractionType.both : UpgradeProxy.InteractionType.notificationbar);
        DownloadTaskDelegate.newInstance ().downloadApk (builder);
    }

    /**
     * 强制更新对话框
     */
    private void createFUGUpdateDialog () {
        ViewDialog.Builder builder = new ViewDialog.Builder (fromActivity);
        // 设置标题
        // builder.setTitle(R.string.forceupgrade_title);
        // 设置信息
        builder.setMessage (R.string.forceupgrade_message);
        // 设置Positive按钮点击监听
        builder.setPositiveButton (R.string.update_version, new DialogInterface.OnClickListener () {

            @Override
            public void onClick (DialogInterface dialog, int which) {
                //                Download.DLoadBindService (fromActivity, URL);
                // 对话框关闭
                checkPermission (true);
                dialog.dismiss ();
            }
        });
        // 设置Negative按钮点击监听
        builder.setNegativeButton (R.string.exit_app, new DialogInterface.OnClickListener () {

            @Override
            public void onClick (DialogInterface dialog, int which) {
                // 对话框关闭
                preferenceUtils.clearVersion ();
                checkVersionListener.finishActivity ();
            }
        });
        // 创建对话框并显示
        builder.setCancelable (false);
        if (null != fromActivity && !((Activity) fromActivity).isFinishing ()) {
            builder.create ().show ();
        }
    }

    public void setCheckActiveListener (OnWhenActiveListener listener) {
        this.mCallback = listener;
    }

    public interface CheckVersionListener {
        void finishActivity ();
    }

    public interface OnWhenActiveListener {
        void checkActive ();
    }
}